﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace WumpusTest
{
	public partial class Form1 : Form
	{
		List<Form1> scores = new List<Form1>();
		private string name;
		private int score;
		private int turns;
		private int gold;
		private int arrows;
		private string date;
		private string place;
		
		public Form1()
		{
			ReadDataFromFile();
		}

		public Form1(string name, int score, int turns, int gold, int arrows, string date, string place)
		{
			// TODO: Complete member initialization
			this.name = name;
			this.score = score;
			this.turns = turns;
			this.gold = gold;
			this.arrows = arrows;
			this.date = date;
			this.place = place;
		}

		private void button1_Click(object sender, EventArgs e, string name, int score, int turns, int gold, int arrows, Boolean demo)
		{
			ReadDataFromFile();
			string date = DateTime.Now.ToString("M/d/yyyy");

			string place;

			if (demo)
			{
				place = "demo";
			}
			else
			{
				place = "random";
			}

			Form1 hs = new Form1(name, score, turns, gold, arrows, date, place);

			scores.Add(hs);

			scores.Sort((Form1 x1, Form1 x2) => score.CompareTo(x2.score));

			scores.Reverse();

			if (scores.Count() > 10)
			{
				scores.Remove(scores[10]);
			}
			writeDataToFile();
			
		}

		public void ReadDataFromFile()
		{
			TextReader tr = new StreamReader("highscores.txt");

			scores = null;
			scores = new List<Form1>();
			string input = tr.ReadLine();

			while (input != null)
			{
				string[] data = input.Split(',');

				Form1 hs = new Form1(data[0], int.Parse(data[1]), int.Parse(data[2]), int.Parse(data[3]), int.Parse(data[4]), data[5], data[6]);

				scores.Add(hs);

				input = tr.ReadLine();
			}

			tr.Close();
		}

		private void writeDataToFile()
		{
			TextWriter tw = new StreamWriter("highscores.txt");

			foreach (Form1 hs in scores)
			{
				string output = hs.name + "," +
								hs.score + "," +
								hs.turns + "," +
								hs.gold + "," +
								hs.arrows + "," +
								hs.place + "," +
								hs.date;
				tw.WriteLine(output);
			}

			tw.Close();
		}

		public List<Form1> Scores
		{
			get { return scores; }
			set { scores = value; }
		}

		private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
		{

		}

		private void button1_Click(object sender, EventArgs e)
		{

		}
	}
}
